import React, {Component} from 'react'
import DefaultLayout from '../../layouts/default_layout'
import TabMenu from '../../layouts/tab_menu'
import {NavBar, List, Button} from 'antd-mobile'
import {withRouter} from 'react-router-dom'
import {post} from '../../common/js/utils'
import {connect} from 'react-redux'
import {setContacts} from '../../actions'
import Loading from '../../components/loading'
import Empty from '../../components/empty'

function mapStateToProps(state, props) {
  return {
    contacts: state.contacts
  }
}

function mapDispatchToProps(dispatch) {
  return {
    setContacts(value) {
      dispatch(setContacts(value))
    }
  }
}

@withRouter
@connect(mapStateToProps, mapDispatchToProps)
class Contact extends Component {

  state = {
    loading: true
  }

  getMyFriends = () => {
    post('/users/getMyFriends').then(res => {
      this.setState({ loading: false })
      this.props.setContacts(res.data)
    })
  }

  componentWillMount() {
    this.getMyFriends()
  }

  chat = (val) => {
    const {history} = this.props
    history.push(`/chat-box?userId=${val._id}`)
  }

  render() {
    const {history, contacts} = this.props
    const {loading} = this.state
    return (
      <DefaultLayout
        header={
          <NavBar
            mode={'dark'}
            rightContent={
              <span
                style={{
                  fontSize: 12
                }}
                onClick={e => history.push('/add')}
              >添加好友</span>
            }
          >联系人</NavBar>
        }
        footer={
          <TabMenu />
        }
      >
        {
          loading && !contacts.length
            ? <Loading />
            : contacts.length
              ? <List className="add-friends-list">
                  {
                    contacts.map((val, key) => (
                      <List.Item
                        style={{
                          minHeight: '65px'
                        }}
                        key={key}
                        extra={
                          <Button
                            type={'ghost'}
                            size={'small'}
                            onClick={e => this.chat(val)}
                          >发消息</Button>
                        }
                        thumb={
                          <div className={'img'}>
                            <img
                              src={val.avatar}
                              alt="用户头像"/>
                          </div>
                        }
                      >{val.nickname}</List.Item>
                    ))
                  }
                </List>
              : <Empty title={'暂无联系人'} />

        }
      </DefaultLayout>
    )
  }
}

export default Contact
